package com.sychip.fhc.app.data.source.dao


import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
import com.sychip.fhc.app.data.source.entity.BleDeviceEntity
import kotlinx.coroutines.flow.Flow

const val TBL_BleDevice = "bleDevice"
/**
 * Data Access Object for the bleDevice table.
 */
@Dao
interface BleDeviceDao {

    /**
     * Observes list of tasks.
     *
     * @return all tasks.
     */
    @Query("SELECT * FROM $TBL_BleDevice")
    fun observeAll(): Flow<List<BleDeviceEntity>>

    /**
     * Observes a single bleDevice.
     *
     * @param devId the bleDevice id.
     * @return the bleDevice with devId.
     */
    @Query("SELECT * FROM bleDevice WHERE devId = :devId")
    fun observeById(devId: String): Flow<BleDeviceEntity>

    /**
     * Select all tasks from the tasks table.
     *
     * @return all tasks.
     */
    @Query("SELECT * FROM bleDevice")
    suspend fun getAll(): List<BleDeviceEntity>

    /**
     * Select a bleDevice by id.
     *
     * @param devId the bleDevice id.
     * @return the bleDevice with devId.
     */
    @Query("SELECT * FROM bleDevice WHERE devId = :devId")
    suspend fun getById(devId: String): BleDeviceEntity?

    /**
     * Insert or update a bleDevice in the database. If a bleDevice already exists, replace it.
     *
     * @param bleDevice the bleDevice to be inserted or updated.
     */
    @Upsert
    suspend fun upsert(bleDevice: BleDeviceEntity)

    /**
     * Insert or update tasks in the database. If a bleDevice already exists, replace it.
     *
     * @param tasks the tasks to be inserted or updated.
     */
    @Upsert
    suspend fun upsertAll(tasks: List<BleDeviceEntity>)

    /**
     * Update the complete status of a bleDevice
     *
     * @param devId id of the bleDevice
     * @param lastConnected status to be updated
     */
    @Query("UPDATE bleDevice SET lastConnected = :lastConnected WHERE devId = :devId")
    suspend fun updateLastConnected(devId: String, lastConnected: String)

    /**
     * Delete a bleDevice by id.
     *
     * @return the number of tasks deleted. This should always be 1.
     */
    @Query("DELETE FROM bleDevice WHERE devId = :devId")
    suspend fun deleteById(devId: String): Int

    /**
     * Delete all tasks.
     */
    @Query("DELETE FROM bleDevice")
    suspend fun deleteAll()

    /**
     * Delete all completed tasks from the table.
     *
     * @return the number of tasks deleted.
     */
    @Query("DELETE FROM bleDevice WHERE isCompleted = 1")
    suspend fun deleteCompleted(): Int
}
